var NBOSS=new (function(){
	var behavior={model:"manage",func:null};
	this.userBehavior=function(model,func){
		if (model || func){
		    behavior.model=model;
            behavior.func=func;
		}
		return behavior;
	};
	var baseUrl='/mgtv/nn_cms_manager_v2';
	this.BaseUrl=function(path){
		if (!path){
			return baseUrl;
		}else{
			___dtree_base_url=path+'/view/public';
			baseUrl=path;
			Starcor.S67.MVC.Application.package = path +'/view/public/mvc';
		}
	};
	var baseHost="http://127.0.0.1/mgtv"
	this.BaseHost=function($host){
		if (!$host){
			return baseHost;
		}else{
			baseHost=$host;
		}
	}
})();



//NBOSS.BaseUrl('/mgtv/nn_cms_manager_v2');

NBOSS.Location=function(){
	var $location=window.location.href;
	var reg=/^http:\/\/(.+?)\/(.+?)(nn_cms_manager_v2|nn_cms_manager)\//ig;
	var $reg_result=reg.exec($location);
	if ($reg_result){
		NBOSS.BaseUrl("/"+$reg_result[2]+"nn_cms_manager_v2");
		NBOSS.BaseHost("http://"+$reg_result[1]+"/"+$reg_result[2]);
	}
}
NBOSS.Location();
NBOSS.Request=function(url){
	return Starcor.S67.$S.Request(url);
};

NBOSS.is_e_back=true;      //是否是后退操作
NBOSS.is_e_default=true;   //是否默认加载cookie指定的页面
NBOSS.dialog=new (function(){
	this.DIALOG_CLOSE='dialog_close';
	this.DIALOG_OPEN='dialog_open';
	this.DIALOG_ACTION='dialog_action';
	this.url='';
	this.params={};
//	弹出框架的名字
    // this.alertmodel;
	this.frameID='alertframe';
	var disEventer={};    
	
	this.disEvent=function(type,data){
		if (typeof disEventer[type] == 'function'){
			disEventer[type](data);
//			if (type==NBOSS.dialog.DIALOG_CLOSE){
//				disEventer={};
//			}
		}
	};
	
	this.open=function(url,title,callback){
		NBOSS.getTopFuc('#myModal');
		if (url){
			this.url=NBOSS.BaseUrl()+'/view/'+url;
			$('#'+this.frameID).attr("src",this.url);
		}
		if(title){
			$('#dailog_head').text(title);
		}
		if(callback){
			$('#dailog_sure').show();
			$('#dailog_sure').unbind().click(function(){
				var sub_obj=$('#alertframe').contents();
				if(callback(sub_obj)){
					$('#myModal').hide();
					$('#'+this.frameID).attr("src",'');
				}	
				// $('#'+this.frameID).attr("src",'');
			})
		}
	};
	
	
	this.addEvent=function(type,func){
		switch(type){
		case this.DIALOG_CLOSE:
			disEventer[this.DIALOG_CLOSE]=func;
			break;
		case this.DIALOG_OPEN:
			disEventer[this.DIALOG_OPEN]=func;
			break;
		case this.DIALOG_ACTION:
			disEventer[this.DIALOG_ACTION]=func;
			break;
		}
	};
})();

NBOSS.reset=function(id){
    if(!id){
        id = "frameBox";
    }
	//外框架重设高度
    var oiframe=document.getElementById(id)?document.getElementById(id):$('#frameBox').contents().find('#'+id)[0];
    var topframe=$('#frameBox')[0];
    try{
    	var availheigth=$(window).height()-125-40-40;
       	var bheight=oiframe.contentWindow.document.body.offsetHeight+50;
       	var max_height=Math.max(bheight,availheigth);
       	var topframe_height=topframe.contentWindow.document.body.offsetHeight+50;
       	var max_topframe_height=Math.max(topframe_height,availheigth);
       	oiframe.style.height=max_height+'px';
       	if($(".main")[0]){
       		$(".main").css('height',max_topframe_height+'px');
       		var nowContentWid=$(".main").width()-$(".left_frame").width()-20;
			 console.log("右边宽度"+nowContentWid);
			$(".right_frame iframe").width(nowContentWid);
       	}
       	// alert(availheigth);
       	// if($(".left_frame")[0]){
       	// 	$(".left_frame").find('iframe').css('height',max_topframe_height+'px');
       	// 	$(".left_frame").find('iframe').contents().find('.leftMenu').css('height',max_topframe_height+'px');
       	// }
       	// // if($(oiframe).parent()){
       	// // 	$(oiframe).parent().css('height',max_height+'px');
       	// // }
       	if($(oiframe).parent()){
       		$(oiframe).parent().css('height',max_height+'px');
       	}
       	document.getElementById('split_btn').style.height=(max_height+39)+'px'; 
    }catch(ex){}
};
NBOSS.subpage_rights=null;
NBOSS.Alert=function(title,msg,options){
	NBOSS.getTopFuc('#myModal2');
	$('#myModal2').find('.modal-title').text(title);
	$('#myModal2').find('.modal-body').text(msg);
	$('#myModal2').find('.modal-footer').children().remove();
	if(options && options.length>0){
		for(var i=0;i<options.length;i++){	
				$('#myModal2').find('.modal-footer').append("<button type='button' id='__alert_btn_"+i+"' class='btn btn-default' data-dismiss='modal'>"+options[i]['btn']+"</button>");
				(function(i){
					var func=options[i]['callback'];
					$("#myModal2 #__alert_btn_"+i).click(function(){
			   			$('#myModal2').hide();
			   			if (typeof func =='function') func();	
			  		});	
				})(i);
		}
	}else{
		$('#myModal2').find('.modal-footer').append("<button type='button' id='__alert_btn_sure' class='btn btn-primary'>确认</button>");
		$("#myModal2 #__alert_btn_sure").click(function(){
			   	$('#myModal2').hide();
			   			
		});	
		
	}	
};
NBOSS.loadingTimeout = null;
NBOSS.requestStatusList = [];
NBOSS.showLoading = function(actionHide){
    var self = this;
    if(actionHide){
        var tempLen = NBOSS.requestStatusList.length;
        var isAllComplate = true;
        if( tempLen > 0){
            for(var i=0; i<tempLen; i++){
                if(!NBOSS.requestStatusList[i].status){
                    isAllComplate = false;
                    break;
                }
            }
        }

        if(!isAllComplate) {
            return null;
        }

        clearTimeout(this.hideLoadTimeout);
        this.hideLoadTimeout = setTimeout(function(){
            clearTimeout( self.loadingTimeout );
            NBOSS.getTopDom('#loading').hide();
            NBOSS.requestStatusList = [];
        },500);
    }else{
        if(NBOSS.getTopDom('#loading').css("display") && NBOSS.getTopDom('#loading').css("display") != "none"){
            clearTimeout(this.hideLoadTimeout);
        }else{
            NBOSS.getTopDom('#loading').show();
            this.animateLoading(0);
        }
    }
};
NBOSS.animateLoading = function(num){
    window.top.$('#loading_images').css("background-position",-(num*100)+"px");
    num ++;
    
    clearTimeout( this.loadingTimeout );
    this.loadingTimeout = setTimeout(function(){
        if(num > 11){
            num = 0;
        }
        NBOSS.animateLoading(num);
    }, 50);
};
NBOSS.tips = {
	alertbox_empty:function(){
		clearTimeout(this.empty_time);
		this.empty_time=window.setTimeout("$('#alertbox').empty()",5000);
	},
	info:function(title,msg,callback){
		$('#alertbox').html("<div class=\"alert alert-info\"><strong>"+title+"</strong>"+msg+"</div>");
		if(typeof callback=='function'){
			callback();
		}
		this.alertbox_empty();
	},
   warning:function(title,msg,callback){
		$('#alertbox').html("<div class=\"alert alert-warning\"><strong>"+title+"</strong>"+msg+"</div>");
		if(typeof callback=='function'){
			callback();
		}
		this.alertbox_empty();
	},
	error:function(title,msg,callback){
		$('#alertbox').html("<div class=\"alert alert-danger\"><strong>"+title+"</strong>"+msg+"</div>");
		if(typeof callback=='function'){
			callback();
		}
		this.alertbox_empty();
	},
	success:function(title,msg,callback){
		$('#alertbox').html("<div class=\"alert alert-success\"><strong>"+title+"</strong>"+msg+"</div>");
		if(typeof callback=='function'){
			callback();
		}
		this.alertbox_empty();
	}
};
//获得父页面dom
NBOSS.getTopDom=function(id){
	return $(id, window.top.document)?$(id, window.top.document):$(id);
};

//使用父页面functions
NBOSS.getTopFuc=function(id){
	$(id).show();
};

//关闭事件，删除对应DOM
	NBOSS.closeDOM=function(id){
	$(id).find('.close').click(function(){
		$(this).parent().remove();
	});
};
var NBOSSJS=[
	{type:'css',src:NBOSS.BaseUrl()+'/view/public/css/common.css'},
	{type:'css',src:NBOSS.BaseUrl()+'/view/public/css/table_control.css'},
	{type:'css',src:NBOSS.BaseUrl()+'/view/public/css/page_control.css'},
	{type:'css',src:NBOSS.BaseUrl()+'/view/public/css/alert.css'},
	{type:'js',src:NBOSS.BaseUrl()+'/view/public/js/common.js'},
	{type:'js',src:NBOSS.BaseUrl()+'/view/public/js/pageControl.js'},
	{type:'js',src:NBOSS.BaseUrl()+'/view/public/js/audio_player.js'},
	{type:'js',src:NBOSS.BaseUrl()+'/view/public/js/ready_function.js'}
];

var __preload_inst=new Starcor.S67.$preLoad();
var __page_complete=false;
var __preload_complete=false;
__preload_inst.setCache(NBOSSJS,function(){
	__preload_complete=true;
		if (__preload_complete && __page_complete){
			NBOSS.__Over();	
		};
});

$(document).ready(function(){
	__page_complete=true;
	if (__preload_complete && __page_complete){
		NBOSS.__Over();	
	};
});


NBOSS.__Over=function(){
	if (typeof NBOSS.Complete =='function') NBOSS.Complete();
	
	$("#myModal #close").live('click',function() {
			$('#myModal').hide();
			$('#alertframe').attr("src",'');
			NBOSS.dialog.params.name='';
        	NBOSS.dialog.disEvent(NBOSS.dialog.DIALOG_CLOSE);
	    });
	    
	    $("#myModal .close").live('click',function() {
	    	$('#myModal').hide();
			$('#alertframe').attr("src",'');
			NBOSS.dialog.params.name='';
	        NBOSS.dialog.disEvent(NBOSS.dialog.DIALOG_CLOSE);
	    }); 
	    $('#'+NBOSS.dialog.frameID).bind('load',function(){
	    	 	NBOSS.dialog.disEvent(NBOSS.dialog.DIALOG_OPEN);
	    	});
	    NBOSS.exTable.init();
}


NBOSS.ajax=function(params,func,callback,model,no_showload){
	if(!no_showload){
		NBOSS.requestStatusList.push({
            "params":params,
            "func":func,
            "status":false
        });
		NBOSS.showLoading(false);
	} 
	if (!model){
		model=window.top.NBOSS.userBehavior().model;
	}
	
	var post_data={
			m:model,
			a:func
			};
	
	for (var attr in params){
		if (!post_data[attr]){
			post_data[attr]=params[attr];
		}
	}
	
	$.ajax(NBOSS.BaseUrl()+"/admin.php",{
		headers:{
			nb_func_id:window.top.NBOSS.userBehavior().func,
		},
		success:function(data){
//			alert(data.reason);
			if(!no_showload){
                for(var i=0; i<NBOSS.requestStatusList.length; i++){
                    if(NBOSS.requestStatusList[i].params == params&&NBOSS.requestStatusList[i].func==func){
                        NBOSS.requestStatusList[i].status = true;
                        break;
                    }
                }
                NBOSS.showLoading(true);
            }
			if (data.code==NBOSS.errCode.NB_STATUS_LOGIN_TIMEOUT){
				window.top.NBOSS.Alert("警告","管理员未登录或登录已超时",[
					{
						'btn':"确定",
						'callback':function(){
							window.top.location.href=NBOSS.BaseUrl()+'/view/index.html';
						}
					}	
				]);
			}else{
				callback(data);
			}
//			managerModel.disEvent('login',data);
		},
		dataType:'json',
		type:'post',
		data:post_data
	});	
};
 NBOSS.arrayAJAX = [];
NBOSS.ajax_v2=function(params,url,callback,no_showload,loading_id){
    if(!no_showload){
        NBOSS.requestStatusList.push({
            "params":params,
            "url":url,
            "status":false
        });
        NBOSS.showLoading(false);
    } else{
        $("#"+loading_id).show();

    }
    var post_data={};
    var infoparams="";
    for (var attr in params){
        if (!post_data[attr]){
            post_data[attr]=params[attr];
            infoparams+=params[attr];
        }
    }

    var urlr=NBOSS.BaseHost()+url;
  var ajaxoption= $.ajax(urlr,{
        success:function(data){
            if(!no_showload){
                for(var i=0; i<NBOSS.requestStatusList.length; i++){
                    if(NBOSS.requestStatusList[i].params == params && NBOSS.requestStatusList[i].url == url){
                        NBOSS.requestStatusList[i].status = true;
                        break;
                    }
                }
                NBOSS.showLoading(true);
            }else {
                $("#"+loading_id).hide();
            }
            callback(data);
        },
        error : function(data){
                if(!no_showload){
	                for(var i=0; i<NBOSS.requestStatusList.length; i++){
	                    if(NBOSS.requestStatusList[i].params == params && NBOSS.requestStatusList[i].url == url){
	                        NBOSS.requestStatusList[i].status = true;
	                        break;
	                    }
	                }
	                NBOSS.showLoading(true);
	            }else {
	                $("#"+loading_id).hide();
	            }
                window.top.NBOSS.Alert('提示', 'Data format error!');
        },
        type:"GET",
        dataType:'json',
        data:post_data
    });
    NBOSS.arrayAJAX.push(ajaxoption);

};

NBOSS.errCode={
	// 成功
		NB_STATUS_OK:'000000',
	// 参数错误
		NB_STATUS_PARAM_ERROR:'100001',
	// 数据库执行失败
		NB_STATUS_SQL_FAIL:'100002',
	// 接口不存在
		NB_STATUS_API_NO_EXIST:'100003',
	// 接口没有访问权限
		NB_STATUS_API_REFUSE:'100004',
	// 数据已存在，数据重复
		NB_STATUS_DATA_EXIST:'100005',
	// 指定的数据不存在
		NB_STATUS_DATA_NO_EXIST:'100006',
	// 用户未登录或登录超时
		NB_STATUS_LOGIN_TIMEOUT:'100007',
/**
 * 许可证码表 
 */ 
//		许可证不合法
		NB_STATUS_LICENCE_ILLEGAL:'110001',
//		没有可发放的许可证
		NB_STATUS_LICENCE_EMPTY:'110002',
/**
 * 产品码表 
 */ 
// 该产品未订购，产品退订失败	
		NB_STATUS_PRODUCT_UNORDER_FAIL:'130001',
/**
 * 用户码表 
 */ 	
		// 用户账户余额不足，无法冻结该款项
		NB_STATUS_USER_FREEZE_ACCOUNT_FAIL:'140001',
		// 用户冻结余额不足，无法解冻该款项
		NB_STATUS_USER_ZHAW_ACCOUNT_FAIL:'140002',
/**
 * 管理员码表 
 */ 
// 管理员不存在，登录失败
		NB_STATUS_MANAGER_NO_EXIST:'150001',
// 管理员密码错误，登录失败
		NB_STATUS_MANAGER_PWD_ERROR:'150002',
// 管理员角色不存在，登录失败
		NB_STATUS_ROLE_NO_EXIST:'150003',	
	
}

/**************TABLE扩展*********************/
NBOSS.exTable={};
NBOSS.exTable.init=function(){
	var $thead_td=$(".exTable").find('thead th');
	var len=$thead_td.length;
	for (var i=0;i<len;i++){
		var html=$thead_td.eq(i).html();
		if ($thead_td.eq(i).hasClass('exTable-nodrag')){
			continue;	
		}
		html = "<span class='exTable-drag-class'></span><span class='exTable-head-label' style='pointer-events:none;'>"+html+"</span>";
		$thead_td.eq(i).html(html);
	}
	
//	-webkit-box-sizing: border-box;
//     -moz-box-sizing: border-box;
//          box-sizing: border-box;
	
	
	
	$(".exTable td.exTable-warp").css({'overflow':'visible','white-space':'normal','text-overflow':'ellipsis'});
	$(".exTable th.exTable-warp").css({'overflow':'visible','white-space':'normal','text-overflow':'ellipsis'});
	var $drag_class=$(".exTable").find('.exTable-drag-class');
	var len2=$drag_class.length;
	for (var j=0;j<len2;j++){
		NBOSS.exTable.drag($drag_class.eq(j)[0]);
	}
	
}

NBOSS.exTable.drag=function(o){
	o.p_p_c_gw=function(index)/*取得o.parentNode.parentNode.cells的宽度，兼容IE6和Firefox*/{ 
		
		if(window.ActiveXObject){ 
			return o.parentNode.parentNode.cells[o.parentNode.cellIndex+index].offsetWidth; 
		}else{
//			var cellPadding=0; 
//			if (o.parentNode.parentNode.parentNode.parentNode.cellPadding) cellPadding=parseInt(o.parentNode.parentNode.parentNode.parentNode.cellPadding);
//			return parseInt(o.parentNode.parentNode.cells[o.parentNode.cellIndex+index].offsetWidth)- 
//			cellPadding*2-2; 
			
			return $(o.parentNode.parentNode.cells[o.parentNode.cellIndex+index]).width();
		} 
	}
	o.p_p_p_sw=function(index,w)/*设置所有行的第index个单元格为w，在IE下可只设第一行*/{ 
		
		for(var i=0;i<o.parentNode.parentNode.parentNode.parentNode.rows.length;i++) { 
			$(o.parentNode.parentNode.parentNode.parentNode.rows[i].cells[index]).width(w);
//			o.parentNode.parentNode.parentNode.parentNode.rows[i].cells[index].style.width=w; 
			//$(o.parentNode.parentNode.parentNode.parentNode.rows[i].cells[index]).css('width',w+"px");
		} 
	} 
	o.doubleClickTimer=null;
	o.onclick=function(a){
		if (o.doubleClickTimer!==null){
			var watch_dog=o.p_p_c_gw(0)+o.p_p_c_gw(1);
			var wid=o.getMaxWid(o.parentNode.cellIndex);
			//wid=wid>=watch_dog?watch_dog:wid;
			var t=	wid-o.p_p_c_gw(0);
			
			o.p_p_p_sw(o.parentNode.cellIndex,o.p_p_c_gw(0)+t); 
			o.p_p_p_sw(o.parentNode.cellIndex+1,o.p_p_c_gw(1)-t);
			
			if(o.p_p_c_gw(0)+o.p_p_c_gw(1)>watch_dog){ 
				o.p_p_p_sw(o.parentNode.cellIndex+1,watch_dog-o.p_p_c_gw(0)); 
			}
			
			clearInterval(o.doubleClickTimer);
			o.doubleClickTimer=null;
		}else{
			o.doubleClickTimer=setTimeout(function(){
				o.doubleClickTimer=null;	
			},500)
		}
	}
	
	o.getMaxWid=function(index){
		var returnWid=$(o.parentNode.parentNode.parentNode.parentNode.rows[0].cells[index]).find('.exTable-head-label').width();
		for(var i=1;i<o.parentNode.parentNode.parentNode.parentNode.rows.length;i++) {
			if ($(o.parentNode.parentNode.parentNode.parentNode.rows[i].cells[index]).hasClass('exTable-warp')) continue;
			//alert('bool:'+$(o.parentNode.parentNode.parentNode.parentNode.rows[i].cells[index]).has('.exTable-tdth'));
			if ($(o.parentNode.parentNode.parentNode.parentNode.rows[i].cells[index]).has('.exTable-tdth-label').length==0){
				var html=$(o.parentNode.parentNode.parentNode.parentNode.rows[i].cells[index]).html();
				$(o.parentNode.parentNode.parentNode.parentNode.rows[i].cells[index]).html('<span class="exTable-tdth-label">'+html+'</span>');
			}
			
			var nowWid=$(o.parentNode.parentNode.parentNode.parentNode.rows[i].cells[index]).find('.exTable-tdth-label').width();
			//alert('nowWid:'+nowWid);
			returnWid= nowWid>returnWid?nowWid:returnWid;
		} 
		return 	returnWid;
	} 
	o.onmousedown=function(a){ 
		var d=document;if(!a)a=window.event; 
		var lastX=a.clientX; 
		var watch_dog=o.p_p_c_gw(0)+o.p_p_c_gw(1);//有时候拖拽过快表格会变大，至于为什么会这样我也不清楚。watch_dog是为了保证表格不会变大， 
		if(o.setCapture) o.setCapture(); 
		else if(window.captureEvents) 
		window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP); 
		// 
		d.onmousemove=function(a){ 
			if(!a)a=window.event; 
			if(o.p_p_c_gw(0)+o.p_p_c_gw(1)>watch_dog){ 
			o.p_p_p_sw(o.parentNode.cellIndex+1,watch_dog-o.p_p_c_gw(0)); 
			return; 
			} 
			var t=a.clientX-lastX;
			// $("#info").html($("#info").html()+"<br>lastX:"+lastX+"|o.parentNode.cellIndex:"+o.parentNode.cellIndex+"|t:"+t+"|p_p_c_gw0:"+o.p_p_c_gw(0)+"|p_p_c_gw1:"+o.p_p_c_gw(1)); 
			if(t>0) {//right 
				if(parseInt($(o.parentNode.parentNode.cells[o.parentNode.cellIndex+1]).width())-t<20) 
				return; 
				
				o.p_p_p_sw(o.parentNode.cellIndex,o.p_p_c_gw(0)+t); 
				o.p_p_p_sw(o.parentNode.cellIndex+1,o.p_p_c_gw(1)-t); 
			} else {//left 
				if(parseInt($(o.parentNode.parentNode.cells[o.parentNode.cellIndex]).width())+t<20) 
				return; 
				o.p_p_p_sw(o.parentNode.cellIndex,o.p_p_c_gw(0)+t); 
				o.p_p_p_sw(o.parentNode.cellIndex+1,o.p_p_c_gw(1)-t); 
			} 
			
			lastX=a.clientX; 
		}; 
		d.onmouseup=function(){ 
			if(o.releaseCapture) 
			o.releaseCapture(); 
			else if(window.captureEvents) 
			window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP); 
			d.onmousemove=null; 
			d.onmouseup=null; 
		}; 
	}; 	
}

